import { system, Vector3, world } from "@minecraft/server";
import { GameComponent } from "@sapi-game/gameComponent";
import { Game } from "@sapi-game/main";
import { Duration, Vector3Utils } from "@sapi-game/utils";
import { DirtShopMainState } from "../states/mainState";

export class DirtShopBed extends GameComponent<DirtShopMainState> {
    protected override onAttach(): void {
        //检测床
        this.subscribe(
            Game.events.interval,
            () => {
                if (this.context.bedExists) {
                    this.checkBed();
                }
            },
            new Duration(10)
        );
        //防止床被房主挖
        this.subscribe(world.beforeEvents.playerBreakBlock, (t) => {
            if (!this.context.host.has(t.player)) return;
            if (this.isBedPos(t.block.location)) {
                t.cancel = true;
                system.run(() => {
                    t.player.onScreenDisplay.setActionBar("你不能破坏自己的床");
                });
            }
        });
        //防止床被炸
        this.subscribe(world.beforeEvents.explosion, (t) => {
            const blocks = t.getImpactedBlocks();
            t.setImpactedBlocks(
                blocks.filter((b) => !this.isBedPos(b.location))
            );
        });
    }

    isBedPos(loc: Vector3) {
        const bedPos = this.context.map.bedPos;
        return (
            Vector3Utils.isEqual(loc, bedPos.head) ||
            Vector3Utils.isEqual(loc, bedPos.tail)
        );
    }

    checkBed() {
        const dim = world.getDimension(this.context.map.region.dimensionId);
        try {
            const block = dim.getBlock(this.context.map.bedPos.head);
            if (block?.typeId !== "minecraft:bed") {
                this.context.bedExists = false;
                this.context.groupSet.title("§c床已被破坏", "房主不能复活");
                this.context.groupSet.forEach((p) => {
                    p.player.playSound("mob.enderdragon.growl", {
                        volume: 0.1,
                    });
                });
            }
        } catch (err) {}
    }
}
